<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="日期">
        <el-date-picker
          v-model="queryParams.date"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="选择日期"
          @change="handleQuery"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="客户" prop="customer">
        <el-select
          v-model="queryParams.customer"
          filterable
          remote
          reserve-keyword
          placeholder="请输入客户"
          clearable
          @change="handleQuery"
          :remote-method="remoteMethod"
          :loading="loading">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="上传部门" prop="uploadDepartment">
        <el-select
          v-model="queryParams.uploadDepartment"
          placeholder="请选择上传部门"
          clearable
          style="width: 240px"
          @change="handleQuery">
          <el-option
            v-for="item in departmentOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>


      <el-form-item label="仓库" prop="wareHouse">
        <el-select
          v-model="queryParams.wareHouse"
          placeholder="请选择仓库"
          clearable
          style="width: 240px"
          @change="handleQuery"
        ><el-option
          v-for="item in wareHouseOptions"
          :key="item"
          :label="item"
          :value="item"
        />
        </el-select>
      </el-form-item>

      <el-form-item label="问题点" prop="problem">
        <el-select
          v-model="queryParams.problem"
          placeholder="请选择问题点"
          clearable
          style="width: 240px"
          @change="handleQuery"
        ><el-option
          v-for="item in problemOptions"
          :key="item"
          :label="item"
          :value="item"
        />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          @click="getDelList"
          v-hasPermi="['system:role:add']"
        >回收站</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleBack"
          v-hasPermi="['system:role:add']"
        >还原</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:role:export']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleExportTemplate"
          v-hasPermi="['system:role:export']"
        >导出模板</el-button>
      </el-col>
      <el-col :span="1.5">
      <el-button
        type="primary"
        plain
        size="mini"
        :disabled="multiple"
        @click="handleEnter"
        v-hasPermi="['system:role:add']"
      >确认</el-button>
    </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleScreenshot"
          v-hasPermi="['system:role:screenshot']"
        >截图</el-button>
      </el-col>

      <!-- 图片详情弹窗 -->
      <el-dialog :visible.sync="pictureDetails" width="50%">
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <!-- 左右切换按钮 -->
          <el-button icon="el-icon-arrow-left" @click="prevImage" :disabled="currentIndex === 0"></el-button>
          <el-image :src="srcList[currentIndex]" fit="contain" style="width: 100%; height: auto;" />
          <el-button icon="el-icon-arrow-right" @click="nextImage" :disabled="currentIndex === srcList.length - 1"></el-button>
        </div>
      </el-dialog>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" prop="id" width="150"  v-if="false"   />
      <el-table-column label="日期" prop="date" width="150"  />
      <el-table-column label="客户" prop="customer" width="110" />
      <el-table-column label="上传部门" prop="uploadDepartment" width="110" />
      <el-table-column label="上传人" prop="uploadPeople" width="110" />
      <el-table-column label="仓库" prop="wareHouse" width="150" />
      <el-table-column label="问题点" prop="problem" width="120" />
      <el-table-column label="异常类型" prop="exceptionType" width="250" />
      <el-table-column label="异常内容描述" prop="exceptionContent" :show-overflow-tooltip="true" width="300" />
<!--      <el-table-column label="截图/资料" prop="screenshot" width="150" />-->
      <el-table-column label="客户异常进度/结果" prop="customerResult" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="确认人/部门" prop="enter" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="是否删除" prop="flagDel"  width="150"  v-if="false"  />
    </el-table>

    <!-- 新增异常处理 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form"  label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="日期">
              <el-date-picker
                v-model="form.date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="选择日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户" prop="customer">
              <el-select
                v-model="form.customer"
                filterable
                remote
                reserve-keyword
                placeholder="请输入客户"
                clearable
                :remote-method="remoteMethod"
                :loading="loading">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="上传部门" prop="uploadDepartment">
              <el-select v-model="form.uploadDepartment" placeholder="请选择上传部门">
                <el-option
                  v-for="item in departmentOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传人" prop="uploadPeople">
              <el-input v-model="form.uploadPeople" placeholder="请输入上传人" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="wareHouse">
              <el-select v-model="form.wareHouse" placeholder="请选择上传部门">
                <el-option
                  v-for="item in wareHouseOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="问题点" prop="problem">
              <el-select v-model="form.problem" placeholder="请选择问题点" @change="handleProblemChange">
                <el-option
                  v-for="item in problemOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="异常类型" prop="exceptionType">
              <el-select v-model="form.exceptionType" placeholder="请选择异常类型" style="width: 200px;">
                <el-option
                  v-for="item in exceptionTwoOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="异常进度" prop="customerResult">
              <el-select v-model="form.customerResult" placeholder="请选择异常进度" >
                <el-option
                  v-for="item in customerResultOptions"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">

            <!--:action里面放图片上传调取的后台方法 :headers设置上传的请求头部,使请求携带自定义token，获取访问权限 -->
            <!--:on-success图片上传成功后的回调方法，用于拿到图片存储路径等信息-->
            <!--:before-upload图片上传前的逻辑判断，例如判断图片大小，格式等-->
            <!--:on-preview图片预览方法 :on-remove图片删除方法   list-type代表文件列表的类型 -->
            <!--file-list存放成功上传图片列表，这里此属性用于修改功能时页面已有图片的显示-->
            <el-form-item label="截图/资料" prop="pictureUrl">
              <el-upload
                :action="imgUpload.url"
                :headers="imgUpload.headers"
                :on-success="handlePictureSuccess"
                :before-upload="beforePictureUpload"
                list-type="picture-card"
                :file-list="fileListShow"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove">
                <i class="el-icon-plus"></i>
              </el-upload>
              <!--图片预览的dialog-->
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="24">
            <el-form-item label="内容描述" prop="exceptionContent">
              <el-input
                v-model="form.exceptionContent"
                type="textarea"
                placeholder="请输入异常内容描述"
                :rows="10"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />



  </div>
</template>

<script>
import { addDept, allList, delDept, backDept, updateDept, detailsForId, enterDept,pictureDetails } from '@/api/amac/exceptionData'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import _ from 'lodash';

export default {
  name: "Role",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,

      // 异常数据导入参数
      upload: {
        // 是否显示弹出层（异常数据导入）
        open: false,
        // 弹出层标题（异常数据导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/amac/exceptionalData/importData"
      },
      //大图片的路劲
      //url:'',
      pictureDetails: false,  // 控制弹窗显示
      srcList: [],  // 存储图片路径的数组
      currentIndex: 0,  // 当前显示图片的索引
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: undefined,
        customer: undefined,
        uploadDepartment: undefined,
        uploadPeople: undefined,
        wareHouse: undefined,
        problem: undefined,
        flagDel:undefined
      },

      //客户下拉框
      options: [],
      value: [],
      list: [],
      states: ["NBMJ","HZTX","HZWS","NBDTK","AJLS","NBYG","NBJRMY","ARTLEON","ZJQL","JTW","XGWJ","ZJJS",
        "NBYBMY","ZJXC","NBYA","JRKJ","NBSY","AJJD","NBRES","NBKX","HNHC","WYD", "ZJTY","ZJMX","HNZT",
        "FZFW","ZJLJJ","HZXC","HZSR","NBYG2","HZQRS","HZMZ","HEX","HZMXR","ZJPD","HZLB","NBQZ","YFS",
        "JKJJ","NBZZ","NBHY","NBHC","NBMW", "LYSLS","NBYX","ZJTYC","LYKJ","AJYB","HZAX","NBML01",
        "YHGJ","NBSQ","NBRTF","NBSQKJ","LYKR","NBCS","JSRQ","HZJCYP","HZJMY","NBJL","YHWL","XGBY",
        "AWS","NBHM","NBYY","ZZANW","XYZN","HNMQ","JXTX","FZQS","XYJJ","SZHK","NBTF","MFL","HZAEF",
        "DYGM","NBAMZN","FSAL","HZMX", "kingshine","FZYS","HZWC","TZMY","AJXG","GLF","LYDZX","SBJJ","YJL","ZZBW"],
      departmentOptions: ['客服', '财务', '销售','操作','其他'],
      wareHouseOptions:['美西一号仓','美西二号仓','美东二号仓','萨瓦纳一号仓'],
      problemOptions:['仓库','物流','系统','渠道/报价','其他'],
      exceptionTypeOptions: {
        '仓库':    ['库内丢件', '错发','多发','卸货时效慢','上架时效慢（客户问题除外）','出库时效问题','操作工单时效','其他--手动填写'],
        '物流':    ['未上网', '拦截失败', '更改地址失败','物流显示送达实际未收到','物流催派'],
        '系统': ['ERP对接问题','渠道对接绑定问题','渠道生成问题，刷不全'],
        '渠道/报价': ['系统报价和实际报价不一致'],
        '其他': ['其他'],
      },
      exceptionTwoOptions:[],
      //异常进度
      customerResultOptions:['沟通中','确认中','已完结','已赔付'],
      //图片上传判断是否有相同图片
      isCommonName: true,
      //修改时此属性用于接收数据库中图片存储list，图片才能正常显示
      fileListShow: [],
      //页面上存的暂时图片地址List
      fileListPut: [],
      dialogImageUrl: '',
      dialogVisible: false,
      imgUpload: {
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 图片上传的方法地址:
        url: process.env.VUE_APP_BASE_API + "/amac/exceptionalData/upload",
        //url2: process.env.VUE_APP_BASE_API,
      },
      // 图片数量限制
      limit: 3,
      //图片地址
      imageUrl: "",
      // 表单参数
      form: {
        date:"",
        customer:"",
        uploadDepartment:"",
        uploadPeople:"",
        wareHouse:"",
        problem:"",
        exceptionType:"",
        customerResult:"",
        exceptionContent:"",
        fileListPut:[]
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.list = this.states.map(item => {
      return { value: item }; // 直接使用值
    });
  },
  methods: {
    /** 查看大图*/
    handleScreenshot(row) {
      // 假设从后端获取图片路径列表
      const bxId = row.bxId || this.ids
      if(bxId.length>1){
        this.$message.error('请选择一条数据');
        return;
      }
      pictureDetails(bxId).then(response => {
        if(response && response.length > 0){
          this.srcList =  response.map(item => item.url);
          if (this.srcList.length > 0) {
            this.pictureDetails = true;  // 打开图片详情弹窗
          } else {
            this.$message.error('没有找到图片');
          }
        }else{
          this.$message.error('没有找到图片');
        }

      });

    },

    // 切换到上一张图片
    prevImage() {
      if (this.currentIndex > 0) {
        this.currentIndex--;
      }
    },

    // 切换到下一张图片
    nextImage() {
      if (this.currentIndex < this.srcList.length - 1) {
        this.currentIndex++;
      }
    },
    /** 客户*/
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.options = this.list.filter(item => {
            return item.value.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.options = [];
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.fileListShow=[]
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id:"",
        date: "",
        customer: "",
        uploadDepartment: "",
        uploadPeople: "",
        wareHouse: "",
        problem: "",
        exceptionType: "",
        exceptionContent: "",
        screenshot: "",
        customerResult: "",
        fileListPut:[]
      };
      //this.resetForm("form");
    },
    handleProblemChange(value) {
      this.form.exceptionType = ''; // 清空异常类型
      // 使用Vue的$set方法确保数组是响应式的
      this.$set(this, 'exceptionTwoOptions', this.exceptionTypeOptions[value]);

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 查询列表 */
    getList() {
      this.queryParams.flagDel =0;
      allList(this.queryParams).then(response => {
        if (!response.rows) return false
        this.roleList=response.rows
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 回收站数据 */
    getDelList() {
      this.queryParams.flagDel =1;
      allList(this.queryParams).then(response => {
        if (!response.rows) return false
        this.roleList=response.rows
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.handleRemove();
      this.title = "异常处理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const bxId = row.bxId || this.ids
      detailsForId(bxId).then(response => {
        console.log("查看图片路劲",this.fileListPut)
        this.fileListShow = JSON.parse(response.fileList);
        this.fileListPut = JSON.parse(response.fileList);
        console.log("所有的图片-修改",this.fileListPut)
        this.form = response;
        this.open = true;
        this.title = "修改异常数据管理";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined ) {
            console.log("this.form.id",this.form.id)
            this.form.fileListPut=JSON.stringify(this.fileListPut)
            updateDept(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.fileListShow=[]
              this.reset();
              this.open = false;
              this.getList();
            });
          } else {
            this.form.fileListPut=JSON.stringify(this.fileListPut)
            addDept(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.fileListShow=[]
              this.open = false;
              this.reset();
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认删除').then(function() {
        return delDept(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("已删除");
      }).catch(() => {});
    },
    //回收站数据还原
    handleBack(row) {
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认还原').then(function() {
        return backDept(userIds);
      }).then(() => {
        this.getDelList();
        this.$modal.msgSuccess("已还原");
      }).catch(() => {});
    },
    /**
     * 确认按钮*/
    handleEnter(row){
      const userIds = row.userId || this.ids;
      this.$modal.confirm('是否确认数据').then(function() {
        return enterDept(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("已确认");
      }).catch(() => {});
    },
    /** 导出模板按钮操作 */
    handleExportTemplate() {
      this.download('amac/exceptionalData/exportTemplate', {
      }, `异常数据模板_${new Date().getTime()}.xlsx`)
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.download('amac/exceptionalData/export', {
      //   ...this.ids
      // }, `user_${new Date().getTime()}.xlsx`)
      axios({
        method: 'post',
        url: process.env.VUE_APP_BASE_API + '/amac/exceptionalData/export',  // 上传的接口地址
        data: this.ids,
        headers: {
          'Content-Type': 'application/json',  // 修改为 application/json
          'Authorization': 'Bearer ' + getToken(),
        },
        onUploadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            onProgress({ percent: percentCompleted });
          }
        },
        responseType: 'blob',  // 如果期望返回二进制文件，设置为 'blob'
      })
        .then((response) => {
          // 处理返回的二进制流
          const blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          });
          const downloadUrl = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = downloadUrl;
          link.download = `异常数据导出_${new Date().getTime()}.xlsx`;
          link.click();
          window.URL.revokeObjectURL(downloadUrl);
          onSuccess(response.data);

        })
        .catch((error) => {
          onError(error);
        })
        .finally(() => {
        });
    },
    beforePictureUpload(file) {
      // 每次进来初始化 isCommonName 为 true
      this.isCommonName = true;
      // 判断文件类型是否为 JPG 或 PNG
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
      // 判断文件大小是否小于 5MB
      const isLt5M = file.size / 1024 / 1024 < 5;

      console.log("图片数量",this.fileListPut.length)
      // 判断是否有相同的图片，如果有则提示并标记为失败
      if (this.fileListPut.length > 0) {
        if(this.fileListPut.length > 2){
          this.$message.error('最多存入三张图片！');
          return false;
        }
        this.fileListPut.forEach((item) => {
          if (item.name === file.name) {
            this.$message.error('已存在相同的图片！');
            this.isCommonName = false;
          }
        });
      }

      // 文件类型和大小验证
      if (!isImage) {
        this.$message.error('请上传 JPG 或 PNG 格式的文件！');
      }
      if (!isLt5M) {
        this.$message.error('上传的图片不能超过 5MB!');
      }

      return isImage && isLt5M && this.isCommonName;
    },
    //图片上传删除
    handleRemove(file) {
      //根据传进来删除的file里图片，同时删除保存在fileListPut的相同图片
      if(this.fileListPut.length > 0){
          let newPut= this.fileListPut.filter(item => item.url !== file.url);
        this.fileListPut=newPut
        }
    },
    //图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片上传成功后的回调
    handlePictureSuccess(res, file){
      //设置图片访问路径
      const imgObjectUrl = file.response.imgUrl;
      console.log("访问路劲",imgObjectUrl)
      //这是每个成功上传图片，以对象的形式保存在一个数组中，进而以JSON格式保存在数据库中某个字段里
      let currentFile = {url: ''};
      currentFile.url = imgObjectUrl;
      //往此数组中保存当前图片对象
      this.fileListPut.push(currentFile);
      console.log(" this.fileListPut", this.fileListPut)
    },
    /**
     * 导入
     */
    handleImport(){
      this.upload.title = "导入异常数据";
      this.upload.open = true;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "导入成功" + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    }
  }
};
</script>
